package cn.lx.feature;


import org.aopalliance.intercept.MethodInterceptor;

import javax.ws.rs.core.Configuration;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import java.lang.annotation.Annotation;
import java.util.List;

/**动态绑定
 * Created by Administrator on 2017/3/14.
 */
public class AOPFeature implements Feature {


    private AOPBingder binder;
    public boolean configure(FeatureContext context) {
        if(binder == null) {
            binder = new AOPBingder();
        }

        context.register(binder);  //绑定是必须的，具体原因在研究
        //获取所有的设置参数
        Configuration configuration = context.getConfiguration();

        //获取拦截器所在的包
        Object obj  = configuration.getProperty(AOPConstants.INTECEPTOR_PACKAGE);
        if(obj == null){
            return false;
        }
        String packages = obj.toString();
        if(packages != null){
            String[] splits = packages.split(",");
            if(splits != null ){
                for(String packageName : splits){

                    //获取到拦截器所在的包
                    List<Class<?>> classes = ClassHelper.getClasses(packageName);

                    for(Class<?> clazz : classes){
                     
                        //注册class
                        regeister(clazz);
                    }
                }
            }

        }
        return true;

    }

    /**
     * 现在操作的是包中的对象，必须是拦截器才进行操作
     * @param clazz
     */
    private void regeister(Class<?> clazz) {

        //判断是否加上了LxAOP注解以及是否是方法拦截器
        if(clazz.isAnnotationPresent(LxAOP.class) && MethodInterceptor.class.isAssignableFrom(clazz)){

            Annotation[] annotations = clazz.getAnnotations();
            if(annotations != null){
                for (Annotation annotation : annotations){
                    if(annotation.annotationType() != LxAOP.class){
                        try {
                            LxMethodInteceptorRegesiter.regeister(annotation.annotationType(),(MethodInterceptor)clazz.newInstance());
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }


    }
}
